#import <Foundation/Foundation.h>
#import <objc/runtime.h>
#import "Debug.h"

#define IBPrefix "ib_"

void IBRename(const char *classname, const char *oldname) {
    Class class = objc_getClass(classname);
    size_t namelen = strlen(oldname);
    char newname[sizeof(IBPrefix) + namelen];
    memcpy(newname, IBPrefix, sizeof(IBPrefix) - 1);
    memcpy(newname + sizeof(IBPrefix) - 1, oldname, namelen + 1);
    Method method = class_getInstanceMethod(class, sel_getUid(oldname));
    if (!class_addMethod(class, sel_registerName(newname), method->method_imp, method->method_types))
        IBLog([NSString stringWithFormat:@"IB: failed to rename %s::%s", classname, oldname]);
}

void IBInitialize() {
	
	if (NSClassFromString(@"SpringBoard") == nil) return;
	
	NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
	
	IBLog(@"IB: changing reason.");
	
	IBRename("SBButtonBar", "leftMarginForIconRowArray:");
	IBRename("SBButtonBar", "initWithFrame:");
	IBRename("SBButtonBar", "originForIconAtX:Y:");
	
	IBRename("SBUIController", "clearLaunchedAfterLanguageRestart");
	
	IBRename("SBIcon", "initWithDefaultSize");
	IBRename("SBIcon", "setInDock:");
	IBRename("SBIcon", "updateLabelOrigin");
	
	NSBundle *bundle = [NSBundle bundleWithPath:@"/Library/Frameworks/FreeBoard.framework"];
  if (bundle == nil)
		IBLog(@"IB: there is no Santa :(");
	else if (![bundle load])
		IBLog(@"IB: sleigh was too heavy");
	else
		IBLog(@"IB: Freedom is a glorious thing!");
	
	[pool release];
}
